<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>AngelScript: Concurrent scripts</title>

<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript">
  $(document).ready(initResizable);
</script>


</head>
<body>
<div id="top"><!-- do not remove this div! -->


<div id="titlearea">
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  
  
  <td style="padding-left: 0.5em;">
   <div id="projectname">AngelScript
   
   </div>
   
  </td>
  
  
  
   
  
 </tr>
 </tbody>
</table>
</div>

<!-- Generated by Doxygen 1.7.5.1 -->
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
  <div id="nav-tree">
    <div id="nav-tree-contents">
    </div>
  </div>
  <div id="splitbar" style="-moz-user-select:none;" 
       class="ui-resizable-handle">
  </div>
</div>
<script type="text/javascript">
  initNavTree('doc_adv_concurrent.html','');
</script>
<div id="doc-content">
<div class="header">
  <div class="headertitle">
<div class="title">Concurrent scripts </div>  </div>
</div>
<div class="contents">
<div class="textblock"><p>The script engine can run multiple scripts in parallel, i.e. concurrent scripts. This can be done easily using <a class="el" href="doc_adv_multithread.html">multithreading</a> where each thread runs its own script context, but this article is going to explain how it is done without multithreading.</p>
<p>In order to execute multiple scripts in parallel, each script must have it's own <a class="el" href="classas_i_script_context.html">asIScriptContext</a>, where the context is set up as for a <a class="el" href="doc_call_script_func.html">normal function call</a>. Then the application needs to set a timeout for each context. When the timeout is reached, the context should be <a class="el" href="classas_i_script_context.html#ad4ac8be3586c46069b5870e40c86544a">suspended</a>, so that the next context can execute for a while.</p>
<p>Here's a very simple example of how this can be done:</p>
<div class="fragment"><pre class="fragment"><span class="comment">// The contexts have already been prepared before this function is called</span>
<span class="keywordtype">void</span> ExecuteScripts(std::vector&lt;asIScriptContext *&gt; contexts)
{
  <span class="comment">// This function will run until all scripts have completed</span>
  <span class="keywordflow">while</span>( contexts.size() &gt; 0 )
  {
    <span class="keywordflow">for</span>( <a class="code" href="angelscript_8h.html#ac8186f029686800b7ce36bde4a55c815" title="32 bit unsigned integer">asUINT</a> n = 0; n &lt; contexts.size(); n++ )
    {
      <span class="comment">// Set a 10 millisecond timeout for this context</span>
      SetTimeoutForContext(contexts[n], 10);

      <span class="comment">// Resume the execution of this context by calling Execute</span>
      <span class="keywordtype">int</span> r = contexts[n]-&gt;Execute();

      <span class="comment">// Remove the timeout so it won&#39;t be triggered accidentally</span>
      RemoveTimeoutForContext();

      <span class="comment">// Determine if the script completed, or was timed out</span>
      <span class="keywordflow">if</span>( r == <a class="code" href="angelscript_8h.html#a867f14b4137dd4602fda1e616b217a69a7b5644be315c46f2fa44f032731242c7" title="The execution is suspended and can be resumed.">asEXECUTION_SUSPENDED</a> )
      {
        <span class="comment">// The script will continue in the next iteration</span>
      }
      <span class="keywordflow">else</span>
      {
        <span class="comment">// The script has completed the execution, so we take it out of the list of scripts</span>
        contexts[n--] = contexts.back();
        contexts.pop_back();
      }
    }
  }
}
</pre></div><p>The application can manage the execution of the scripts in a simple round-robin fashion, where each script gets equal amount of execution time, or a more intricate management algorithm can be built, e.g. to give more execution time to high priority scripts etc.</p>
<p>The time out function, i.e. SetTimeoutForContext in the example above, can be implemented in two different ways. Through the use of <a class="el" href="classas_i_script_context.html#ae2747f643bf9a07364f922c460ef57dd">line callbacks</a>, where the context will invoke the callback for each statement in the script. The callback can then check if the timeout limit has been reached and suspend the context.</p>
<p>The other way is through the use of a timeout thread, where the thread simply sleeps until the timeout limit has been reached, and when the thread wakes up it suspends the context (if it is still running).</p>
<p>The timeout thread is probably the easiest to implement, and also doesn't impact the performance as much as the line callback. The line callback may still have to be used if the target OS doesn't support multithreading though.</p>
<p>Here's a simple example of how to implement the timeout function with a separate thread:</p>
<div class="fragment"><pre class="fragment"><span class="keyword">static</span> HANDLE            thread_handle = 0;
<span class="keyword">static</span> <a class="code" href="classas_i_script_context.html" title="The interface to the virtual machine.">asIScriptContext</a> *thread_ctx;

DWORD WINAPI TimeoutThread(<span class="keywordtype">void</span> *sleeptime)
{
  Sleep(*reinterpret_cast&lt;int*&gt;(sleeptime));
  <span class="keywordflow">if</span>( thread_ctx )
    thread_ctx-&gt;<a class="code" href="classas_i_script_context.html#ad4ac8be3586c46069b5870e40c86544a" title="Suspends the execution, which can then be resumed by calling Execute again.">Suspend</a>();

  <span class="keywordflow">return</span> 0;
}

<span class="keywordtype">void</span> SetTimeoutForContext(<a class="code" href="classas_i_script_context.html" title="The interface to the virtual machine.">asIScriptContext</a> *ctx, <span class="keywordtype">int</span> milliseconds)
{
  thread_ctx    = ctx;
  thread_handle = CreateThread(0, 50, TimeoutThread, reinterpret_cast&lt;void*&gt;(&amp;milliseconds), 0, 0);
}

<span class="keywordtype">void</span> RemoveTimeoutForContext()
{
  <span class="comment">// TerminateThread should be used with extreme care, but in this </span>
  <span class="comment">// case the TimeoutThread can&#39;t do any harm even if interrupted </span>
  <span class="comment">// in the middle of the execution</span>
  TerminateThread(thread_handle, 0);
  thread_handle = 0;
}
</pre></div><p>Observe that the routines for multithreading usually differ a lot depending on the target system. The above code is for Windows and will most likely require adaption to work on any other system.</p>
<dl class="see"><dt><b>See also:</b></dt><dd><a class="el" href="doc_addon_ctxmgr.html">Context manager</a>, <a class="el" href="doc_samples_concurrent.html">Concurrent scripts</a>, <a class="el" href="doc_adv_coroutine.html">Co-routines</a> </dd></dl>
</div></div>
</div>
  <div id="nav-path" class="navpath">
    <ul>

    <li class="footer">Generated on Sun Jan 29 2012 15:41:03 for AngelScript by
    <a href="http://www.doxygen.org/index.html">
    <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.5.1 </li>
   </ul>
 </div>


</body>
</html>
